$(function (){
    var  href = location.href;
    let fid =(Number)(href.substring(href.indexOf("=")+1));


    //更新消息并排序
    function updateChat(sentData,receiptData) {
        // 用于存储所有消息的数组
        var allMessages = [];
        sentData.forEach(function (sdata){
            let sentMessage = sdata.split("?")[0];
            let sentTime = new Date(sdata.split("?")[1]);
            var newMessage={
                text: sentMessage,
                time: sentTime,
                sender: 'send'  // 添加一个属性表示发送者
            }
            allMessages.push(newMessage);
        })
        receiptData.forEach(function (rdata){
            let sentMessage = rdata.split("?")[0];
            let sentTime = new Date(rdata.split("?")[1]);
            var newMessage={
                text: sentMessage,
                time: sentTime,
                sender: 'receipt'  // 添加一个属性表示接收者
            }
            allMessages.push(newMessage);
        })
        // 清空聊天记录
        $(".msg").empty();

        // 对消息数组按时间进行排序
        allMessages.sort(function(a, b) {
            return a.time - b.time;
        });
        // 如果没有消息，显示 "无聊天内容，开始聊天"
        if (allMessages.length === 0) {
            $(".msg").html('<a class="no-data">我通过了你的朋友验证请求,现在我们可以开始聊天了</a>');
            return;
        }
        // 按排序后的顺序插入消息
        allMessages.forEach(function(msg) {
            if (msg.sender === 'send') {
                $(".msg").append(`<div class="clearfix">
                <div class="f">
                    <div class="info send">
                        <img src="${sentImg}" />
                        <time>${formatDate(msg.time)}</time>
                    </div>
                    <div class="text">${msg.text}</div>
                </div>
            </div>`);
            } else if (msg.sender === 'receipt') {
                $(".msg").append(`<div class="clearfix">
                <div class="t">
                    <div class="info receipt">
                        <img src="${receiptImg}" />
                        <time>${formatDate(msg.time)}</time>
                    </div>
                    <div class="text">${msg.text}</div>
                </div>
            </div>`);
            }
        })
    }
    var init = function (){
        //初始化数据
        $.get("chat/init",{fid:fid},function (data) {
            var infrom_list = data.infrom;
            var offical_list = data.offical;
            var userdata = data.userData;
            var friendData = data.friendData;
            myUser = data.myUser;
            console.log(data)
            var sum = data.sum;
            //回写数量
            //数量字符串
            let str = sum[0];
            let sum_list = +str.split("-");
            $("#osum").text(sum_list[0])
            $("#isum").text(sum_list[1])


            //回写官方消息
            offical_list.forEach(function (date) {
                let content = date.substring(0, date.lastIndexOf("?"));
                let time = date.substring(date.lastIndexOf("?") + 1, date.length);
                $("#msg-offical").append(`<a class="msg" href="">
            <span>${content}</span>
            <time>${time}</time>
            </a>`);
            })
            //回写通知消息
            infrom_list.forEach(function (date) {
                let content = date.substring(0, date.lastIndexOf("?"));
                let time = date.substring(date.lastIndexOf("?") + 1, date.length);
                $("#msg-infrom").append(`<a class="msg" href="">
			<span>${content}</span>
			<time>${time}</time>
			</a>`);
            })
            //回写好友列表
            friendData.forEach(function (data) {
                let a = data.split("?");
                let name = a[0];
                let img = a[1];
                let id = +a[2]
                $("#user_List").append(`<a class="data" id="${id}"><img src="${img}"/><em>${name}</em><b class="dot"></b></a>`)
            })


            //回写黑名单
            userdata.forEach(function (data) {
                let a = data.split("?");
                let name = a[0];
                let img = a[1];
                let black_id=a[2];
                $("#msg-black").append(`<a class="msg" id="b_${black_id}">
            <span><img src="${img}"/>${name}</span>
            <button class="btn" id="remove_black">解除</button>
            </a>`)
            })

            let size = $(".data").length;


            //点击聊天事件
            $("#user_List").on("click", ".data", function () {
                $(this).addClass("active").siblings().removeClass("active")
                $(this).find("em");
                //写入昵称
                $(".clearfix .name").text($(this).find("em").text())
                //写入头像
                $(this).find("img").prop("src")
                $(".send").find("img").prop("src", $(this).find("img").prop("src"))


                $.get("chat/chatRecord", {id: $(this).prop("id")}, function (data) {
                    $(".msg").empty();
                    console.log(data)
                    let sentData = data.sentList;
                    let receiptData = data.receiptList
                    sentImg = data.sendImg[0];
                    receiptImg = data.receiptImg[0];
                    console.log("a", sentImg)
                    console.log(receiptImg)
                    sentData.forEach(function (data) {
                        let sentMessage = data.split("?")[0];
                        let sentTime = data.split("?")[1];
                        $(".msg").append(`<div class="f">
                    <div class="info send" >
                     <img src="${sentImg}" />
                     <time>${sentTime}</time>
                     </div>
                     <div class="text">${sentMessage}</div>
                     </div>`)
                    })
                    receiptData.forEach(function (data) {
                        let sentMessage = data.split("?")[0];
                        let sentTime = data.split("?")[1];
                        $(".msg").append(`<div class="clearfix">
                    <div class="t">
                    <div class="info receipt">
                    <img src="${receiptImg}" />
                    <time>${sentTime}</time>
                    </div>
                    <div class="text">${sentMessage}</div>
                    </div>
                    </div>`);
                    })
                    updateChat(sentData,receiptData);
                })
            })
            $("#user_List").on("click", ".data", function () {
                // 解绑之前的点击事件处理程序
                $("#sendMessage").off("click");
                // 绑定新的点击事件处理程序
                $("#sendMessage").on("click", function () {
                    // 处理发送消息的逻辑
                    var message = $(".textMessage").val();
                    var nowTime = getTime();
                    $(".textMessage").val("");
                    $(".msg").append(`<div class="clearfix">
                <div class="t">
                <div class="info receipt">
                <img src="${receiptImg}" />
                <time>${nowTime}</time>
                </div>
                <div class="text">${message}</div>
                </div>
                </div>`);
                    // 滚动到页面底部
                    $("html, section").animate({scrollTop: $(document).height()}, "slow");
                    //更新到数据库
                    let recept =$("#user_List").find(".active").prop("id");
                    $.post("chat/updateChat",{"recept":recept,"content":message,"time":nowTime})

                })
            })

            //点击加入黑名单
            $("#black_btn").click(function (){
                let activeUserId = $("#user_List").find(".active").prop("id");
                alert("拉黑成功！")
                $.get("chat/addBlack",{"blickId":activeUserId},function () {
                       location.reload()
                })


            })
            var getTime = function () {
                var currentDate = new Date();
                var year = currentDate.getFullYear();
                var month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
                var day = String(currentDate.getDate()).padStart(2, '0');
                var hours = String(currentDate.getHours()).padStart(2, '0');
                var minutes = String(currentDate.getMinutes()).padStart(2, '0');
                var seconds = String(currentDate.getSeconds()).padStart(2, '0');
                var formattedDateTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
                return formattedDateTime;
            }
            //回写自己头像
            var user = myUser[0].split("?");
            var name = user[0];
            var img = user[1];
            ;
            console.log(img)
            $(".receipt").find("img").prop("src", img);

        })
    }

    //解除黑名单
    $("#msg-black").on("click",".msg",function (){

        let b_id = $(this).prop("id").substring(2);
        $.get("chat/removeBlack",{"backId":b_id},function (){
        alert("解除成功！")
            location.reload();
        })
    })
    function updateMessage(data) {

    }
    init();
    //聊天实时刷新
    startChatRefresh();
    updateMessage();
    //通知实时刷新
    startMessageRefresh();




    function startChatRefresh() {
        intervalId = setInterval(function() {
            // 这里可以调用刷新聊天的逻辑
            var activeUserId = $("#user_List").find(".active").prop("id");
            if (!activeUserId) {
                return; // 如果没有活动用户，不执行刷新
            }

            $.get("chat/chatRecord", { id: activeUserId }, function(data) {
                // 处理刷新聊天的逻辑，更新消息等
                console.log(data)
                let sent =  data.sentList;
                let res = data.receiptList
                // 调用 updateChat 函数来更新消息
                updateChat(sent, res);
            });
        }
        , 2000); // 2000 毫秒（2秒）为刷新间隔
    }

    function startMessageRefresh(){

        setInterval(function (){
            $.get("chat/updateMessage",function (data){
                $("#msg-infrom").empty();
                $("#msg-offical").empty();
                console.log(data)
                let black  =  data.black;
                let infrom =  data.infrom;
                let offical = data.offical;
                let friend = data.friend[0];
                let f_d = friend.split("-");
                $("#isum").text(infrom.length)
                $("#osum").text(offical.length)
                $("#psum").text(f_d.length)

                infrom.forEach(function (data){
                    let content = data.split("?")[0];
                    let time = data.split("?")[1];
                    $("#msg-infrom").append(`<a class="msg" href="">
			        <span>${content}</span>
			        <time>${time}</time>
		        	</a>`);
                })
                offical.forEach(function (data){
                    let content = data.split("?")[0];
                    let time = data.split("?")[1];
                    $("#msg-offical").append(`<a class="msg" href="">
                    <span>${content}</span>
                    <time>${time}</time>
                    </a>`);
                })
                //      updateMessage(data);
            })
        },2000);

    }




    // 当用户点击 "发送消息" 按钮时
    $("#sendMessage").on("click", function () {
        var message = $(".textMessage").val();
        var nowTime = getTime();


        console.log("情况 达瓦达瓦")
        // 创建一个新消息对象，包括消息文本和时间
        var newMessage = {
            text: message,
            time: new Date(nowTime)
        };

        // 添加新消息到数组
        allMessages.push(newMessage);
        // 对消息数组按时间进行排序
        allMessages.sort(function (a, b) {
            // 按时间升序排序
            return a.time - b.time;
        });
        // 清空聊天记录
        $(".msg").empty();
        // 按排序后的顺序插入消息
        allMessages.forEach(function (msg) {
            $(".msg").append(`<div class="clearfix">
                <div class="t">
                    <div class="info receipt">
                        <img src="${receiptImg}" />
                        <time>${formatDate(msg.time)}</time>
                    </div>
                    <div class="text">${msg.text}</div>
                </div>
            </div>`);
        });

        // 滚动到页面底部
        $("html, section").animate({ scrollTop: $(document).height() }, "slow");
        $(".textMessage").text("");
    });
    // 获取当前时间的格式化字符串
    function getTime() {
        var currentDate = new Date();
        // ...
    }
    // 格式化日期为 "YYYY-MM-DD HH:MM:SS" 格式
    function formatDate(date) {
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');
        var seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

})